package com.admin.web.controller;

import com.admin.bean.AppUserContext;
import com.admin.bean.HttpResult;
import com.admin.model.AppUser;
import com.admin.model.WatchHistory;
import com.admin.repository.mongo.WatchHistoryRepository;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/app/watchHistory")
@RestController
public class WatchHistoryController {

    @Resource
    private WatchHistoryRepository watchHistoryRepository;

    @RequestMapping("/getWatchHistorys")
    public HttpResult<Page<WatchHistory>> getWatchHistorys(@RequestBody JSONObject jsonObject) {
        Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "watchTime"));
        int page = jsonObject.getIntValue("page");
        Pageable pageable = new PageRequest(page, 20, sort);
        AppUser appUser = AppUserContext.getAppUser();
        Page<WatchHistory> result = watchHistoryRepository.findByAppUserId(appUser.getId(), pageable);
        return HttpResult.buildSuccess(result);
    }

    @RequestMapping("saveWatchhistory")
    public HttpResult<Void> saveWatchhistory(@RequestBody WatchHistory watchHistory) {

        watchHistory.setAppUserId(AppUserContext.getAppUser().getId());
        WatchHistory dbWatchHistory = watchHistoryRepository.findByAppUserIdAndUrl(watchHistory.getAppUserId(), watchHistory.getUrl());
        if(dbWatchHistory != null){
            dbWatchHistory.setWatchTime(System.currentTimeMillis());
            watchHistory = dbWatchHistory;
        }
        watchHistoryRepository.save(watchHistory);
        return HttpResult.buildSuccess(null);
    }
}
